<template>
  <div class="container mx-auto p-4">
    <h1 class="text-2xl font-bold mb-4">API 连接测试</h1>
    
    <div class="mb-6">
      <h2 class="text-xl font-semibold mb-2">配置信息</h2>
      <div class="bg-gray-100 p-4 rounded">
        <p><strong>API 头部URL:</strong> {{ apiHeadUrl }}</p>
        <p><strong>API 基础URL:</strong> {{ apiBaseUrl }}</p>
        <p><strong>API 域名:</strong> {{ apiDomain }}</p>
        <p><strong>环境:</strong> {{ isProd ? '生产环境' : '开发环境' }}</p>
      </div>
    </div>
    
    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
      <div>
        <button @click="testDirectConnection" class="bg-blue-500 text-white px-4 py-2 rounded mb-2">
          测试直接连接
        </button>
        <div v-if="directResult" class="mt-2">
          <div v-if="directResult.success" class="text-green-600">
            连接成功!
          </div>
          <div v-else class="text-red-600">
            连接失败: {{ directResult.error }}
          </div>
        </div>
      </div>
      
      <div>
        <button @click="testProxyConnection" class="bg-green-500 text-white px-4 py-2 rounded mb-2">
          测试代理连接
        </button>
        <div v-if="proxyResult" class="mt-2">
          <div v-if="proxyResult.success" class="text-green-600">
            连接成功!
          </div>
          <div v-else class="text-red-600">
            连接失败: {{ proxyResult.error }}
          </div>
        </div>
      </div>
    </div>
    
    <div>
      <button @click="testSimulationAPI" class="bg-purple-500 text-white px-4 py-2 rounded mb-2">
        测试模拟请求
      </button>
      <div v-if="simulationResult" class="mt-2">
        <div v-if="simulationResult.success" class="text-green-600">
          模拟请求成功!
          <pre class="bg-gray-100 p-2 mt-2 rounded text-xs">{{ JSON.stringify(simulationResult.data, null, 2) }}</pre>
        </div>
        <div v-else class="text-red-600">
          模拟请求失败: {{ simulationResult.error }}
        </div>
      </div>
    </div>
    
    <div class="mt-6">
      <h2 class="text-xl font-semibold mb-2">请求日志</h2>
      <div class="bg-gray-100 p-4 rounded h-64 overflow-y-auto">
        <div v-for="(log, index) in logs" :key="index" class="mb-2">
          <div :class="log.type === 'error' ? 'text-red-600' : 'text-green-600'">
            {{ log.message }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { API_CONFIG, API_HEAD_URL } from '../api-config';
import api from '../logic/api';

export default {
  name: 'ApiTestPage',
  data() {
    return {
      apiBaseUrl: API_CONFIG.BASE_URL,
      apiDomain: API_CONFIG.API_DOMAIN,
      apiHeadUrl: API_HEAD_URL,
      isProd: import.meta.env.PROD,
      directResult: null,
      proxyResult: null,
      simulationResult: null,
      logs: []
    };
  },
  methods: {
    addLog(message, type = 'info') {
      this.logs.unshift({
        message: `[${new Date().toLocaleTimeString()}] ${message}`,
        type
      });
    },
    
    async testDirectConnection() {
      this.directResult = null;
      this.addLog('测试直接连接到API服务器...');
      
      try {
        const response = await fetch(`${API_HEAD_URL}/api/statistics`);
        const data = await response.json();
        
        this.addLog('直接连接成功');
        this.directResult = { success: true, data };
      } catch (error) {
        this.addLog(`直接连接失败: ${error.message}`, 'error');
        this.directResult = { success: false, error: error.message };
      }
    },
    
    async testProxyConnection() {
      this.proxyResult = null;
      this.addLog('测试通过代理连接到API服务器...');
      
      try {
        const response = await fetch('/api/statistics');
        const data = await response.json();
        
        this.addLog('代理连接成功');
        this.proxyResult = { success: true, data };
      } catch (error) {
        this.addLog(`代理连接失败: ${error.message}`, 'error');
        this.proxyResult = { success: false, error: error.message };
      }
    },
    
    async testSimulationAPI() {
      this.simulationResult = null;
      this.addLog('测试模拟API...');
      
      try {
        // 先获取一个策略表ID
        const tables = await api.betStrategyTables.getAll();
        
        if (!tables || tables.length === 0) {
          throw new Error('没有找到策略表');
        }
        
        const tableId = tables[0].id;
        this.addLog(`使用策略表ID: ${tableId}`);
        
        // 准备模拟参数
        const simulationParams = {
          strategy_name: 'API测试',
          max_rounds: 100,
          deck_seed: Math.floor(Math.random() * 1000000),
          parameters: {
            observation_rounds: 6,
            strategy_table_id: tableId
          }
        };
        
        this.addLog(`发送模拟请求，参数: ${JSON.stringify(simulationParams)}`);
        const result = await api.simulations.run(simulationParams);
        
        this.addLog('模拟请求成功');
        this.simulationResult = { success: true, data: result };
      } catch (error) {
        this.addLog(`模拟请求失败: ${error.message}`, 'error');
        this.simulationResult = { success: false, error: error.message };
      }
    }
  }
};
</script> 